﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Model;
using DispatchAssist.Model;
using CarolLib.WinService;
using CarolLib;
using System.Collections;

namespace DispatchAssist.SMSMessageGenerator
{
    public class Generator:IBasicTask
    {
        #region members

        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static MessageCreateManger manger;

        #endregion

        #region implete IbasicTask

        public void Init()
        {
            manger = new MessageCreateManger();
        }


        public void Execute()
        {
            //step 1. 获取符合条件的预警信息

            List<SMSAlertAllInfo> source;

            try
            {
                source = manger.GetNecessarySMSAlert(Enums.AlertActionFlag.AutoSendSMSAlert | Enums.AlertActionFlag.ConfirmSMS, Enums.AlertActionFlag.AutoSendSMSAlert);

                Logger.InfoFormat(" there is {0} messages", source.Count);
            }
            catch (Exception e)
            {
                Logger.Error("error in get SMS ALert INFO", e);

                return;
            }

            if (source == null || source.Count == 0)
            {
                return;
            }

            List<string> successIDs = new List<string>();

            int count = 0;
            foreach (SMSAlertAllInfo info in source)
            {
                //step 2.获取模板信息

                MsgTemplate temInfo;

                try
                {
                    temInfo = GetTempleteInfo((int)(Enums.AlertActionFlag.AutoSendSMSAlert | Enums.AlertActionFlag.ConfirmSMS));
                }
                catch (Exception e)
                {
                    Logger.Error("get Auto Send SMS Template Error", e);
                    continue;
                }

                string messageBody = "";
                try
                {
                    messageBody = MessageBodyFactory.GetMessageBody<SMSAlertAllInfo>(info, temInfo.MsgContent);

                }
                catch (Exception e)
                {
                    Logger.Error("create SMS message body error", e);

                    continue;
                }

                //step 3. 获取需要发送的所有手机号

                List<SMSContact> contactList = GetContactList(info.GroupCode);

                if (contactList.Count == 0)
                {
                    if (!successIDs.Contains(info.SMSAlertID.ToString()))
                    {
                        successIDs.Add(info.SMSAlertID.ToString());
                    }
                    continue;
                }


                count++;
                string sn = DateTime.Now.ToString("yyMMddhhmmssfff")+count.ToString();

                foreach (SMSContact contact in contactList)
                {
                    try
                    {

                        //step 4. 创建消息实体并插入数据库
                        CreateSMSMsg(info.SMSAlertID, contact.ContactMobile, messageBody,sn);

                        if (!successIDs.Contains(info.SMSAlertID.ToString()))
                        {
                            successIDs.Add(info.SMSAlertID.ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(string.Format("Insert SMS MSg Error messageBody:{0}", messageBody), e);
                        continue;
                    }
                }


            }

            //step5. 更新状态

            try
            {
                manger.UpdateSMSAlertStatus(successIDs.ToArray(), Enums.AlertActionFlag.AutoSendSMSAlert);
            }
            catch (Exception e)
            {
                Logger.Error(" error in update SMS Alert Status",e);
            }
        }


        public void Exit()
        {
            
        }

        #endregion

        #region private method

        private MsgTemplate GetTempleteInfo( int actionFlag)
        {
            return CommonCacheData.CacheTemplate.GetTemplateByPara(actionFlag, null);
        }

        private List<SMSContact> GetContactList(string companyCode)
        {
            List<SMSContact> list = new List<SMSContact>();
            try
            {
                list= manger.GetContactList(companyCode);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
            return list;
        }

        private void CreateSMSMsg(Guid AlertID, string MobileNo, string MessageBody,string SN)
        {
            SMSMsg model = new SMSMsg();

            model.SMSAlertID = AlertID;
            model.GroupSN = decimal.Parse(SN);
            model.MobileNo = MobileNo;
            model.MsgBody = MessageBody;
            model.MsgStatus = (int)Enums.MessageStatus.FinishCreate;

            manger.InertSMSMessageModel(model);
        }

        #endregion
    }
}
